package com.example.word.ui.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.word.MyApplication;
import com.example.dict.R;
import com.example.word.adapter.DictAdapter;
import com.example.word.bean.Dict;
import com.example.word.bean.User;
import com.example.word.bean.Word;
import com.example.word.ui.activity.AddActivity;
import com.example.word.ui.activity.AddWordActivity;
import com.example.word.ui.activity.LoginActivity;
import com.example.word.ui.activity.MainActivity;
import com.example.word.ui.activity.OpeningActivity;
import com.example.word.ui.activity.UnitActivity;
import com.example.word.util.CommonUtils;
import com.example.word.util.ExceptionUtils;
import com.example.word.util.HttpUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.util.StringUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;


/**
 * 主页Fragment
 */

public class HomeFragment extends Fragment {

    public static List<String> state = Arrays.asList("0", "1", "2", "3");

    public static List<String> title = Arrays.asList("基础教育", "高等教育", "出国考试", "其他词汇");

    private String[] selectViews = new String[]{"新增词汇", "新增单词", "删除单词"};
    private int selectViewIndex;

    private Activity myActivity;//上下文
    private TabLayout tabTitle;
    private RecyclerView rvDictList;
    private DictAdapter dictAdapter;
    private LinearLayout llEmpty;
    private Boolean mIsAdmin;
    private String mAccount;//账号
    private FloatingActionButton btnAdd;
    private String typeId = "0";
    private List<Dict> dictList;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        myActivity = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        tabTitle = (TabLayout) view.findViewById(R.id.tab_title);
        rvDictList = (RecyclerView) view.findViewById(R.id.rv_dict_list);
        llEmpty = view.findViewById(R.id.ll_empty);
        btnAdd = (FloatingActionButton) view.findViewById(R.id.btn_add);
        //获取控件
        initView();
        //加号点击事件
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(mAccount)) {//未登录,跳转到登录页面
                    MyApplication.Instance.getMainActivity().finish();
                    startActivity(new Intent(myActivity, LoginActivity.class));
                    return;
                }

                if (true) {
                    //打开新增词汇页面
                    Intent intent = new Intent(myActivity, AddActivity.class);
                    startActivityForResult(intent, 100);
                    return;
                }

                // 以下代码暂不会执行
                AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
                builder.setIcon(R.drawable.a1);//设置图标
                builder.setTitle("功能列表");//设置对话框的标题
                builder.setSingleChoiceItems(selectViews, 0, (dialog, which) -> {
                    selectViewIndex = which;
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (selectViewIndex == 0) {
                                    //打开新增词汇页面
                                    Intent intent = new Intent(myActivity, AddActivity.class);
                                    startActivityForResult(intent, 100);
                                }
                                if (selectViewIndex == 1) {
                                    //打开新增单词页面
                                    Intent intent = new Intent(myActivity, AddWordActivity.class);
                                    startActivityForResult(intent, 100);
                                }
                                if (selectViewIndex == 2) {
                                    //删除单词
                                    Intent intent = new Intent(myActivity, AddWordActivity.class);
                                    startActivityForResult(intent, 100);
                                }
                            }
                        }
                );
                builder.setNegativeButton("取消", (dialog, which) -> {
                });
                AlertDialog a = builder.create();
                a.show();
            }
        });
        return view;
    }

    public void clickDelete() {
        AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
        builder.setIcon(R.drawable.a1);//设置图标
        builder.setTitle("删除单词");
        // 创建一个 EditText 控件用于输入
        final EditText inputEditText = new EditText(myActivity);
        inputEditText.setHint("请输入要删除的单词");
        builder.setView(inputEditText);
        // 设置对话框的积极按钮（确定按钮）以及点击事件
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 在这里处理确定按钮的点击事件，可以获取输入框中的文本
                String userInput = inputEditText.getText().toString();
                List<Word> exist = Word.where("word = ?", userInput.replace("'", "''")).find(Word.class);
                if (exist.isEmpty()) {
                    MessageUtils.show("输入单词不存在，删除失败", myActivity);
                    return;
                }

                for (Word word : exist) {
                    word.delete();
                }
                MessageUtils.show("删除成功", myActivity);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", (dialog, which) -> loadData()
        );
        AlertDialog a = builder.create();
        a.show();
    }

    /**
     * 初始化页面
     */
    private void initView() {
        mIsAdmin = (Boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
        mAccount = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        btnAdd.setVisibility(mIsAdmin ? View.VISIBLE : View.GONE);
        tabTitle.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置tablayout距离上下左右的距离
        // tabTitle.setPadding(20,20,20,20);
        //为TabLayout添加tab名称
        for (int i = 0; i < title.size(); i++) {
            tabTitle.addTab(tabTitle.newTab().setText(title.get(i)));
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        rvDictList.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        dictAdapter = new DictAdapter(llEmpty, rvDictList);
        //=2.3、设置recyclerView的适配器
        rvDictList.setAdapter(dictAdapter);
        loadData();
        dictAdapter.setItemListener(new DictAdapter.ItemListener() {
            @Override
            public void ItemClick(Dict dict) {
                boolean isAdmin = (boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
                String account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
                if ("".equals(account)) {//未登录,跳转到登录页面
                    MyApplication.Instance.getMainActivity().finish();
                    startActivity(new Intent(myActivity, LoginActivity.class));
                } else {//已经登录
                    Intent intent = null;
                    if (isAdmin) {
                        intent = new Intent(myActivity, AddActivity.class);
                        intent.putExtra("dict", dict);
                        startActivityForResult(intent, 100);
                    } else {
                        // 判断是否已经下载过
                        ProgressDialog dialog = new ProgressDialog(myActivity);
                        dialog.setMessage("正在加载单词···");
                        dialog.show();
                        // 去有道词典下载词汇
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                if (!"downloaded".equals(dict.getWordFileUrl())) {
                                    // 开始远程下载
                                    // saveWord(dict.getWordFileUrl(), dict.getTitle());
                                    OkHttpClient client = new OkHttpClient();
                                    Request request = new Request.Builder().url(dict.getWordFileUrl()).build();

                                    client.newCall(request).enqueue(new Callback() {
                                        @Override
                                        public void onResponse(Call call, Response response) {
                                            if (response.isSuccessful()) {
                                                // 创建目标文件夹
                                                // 获取应用的私有目录
                                                File folder = myActivity.getExternalFilesDir(null);
                                                // 保存下载的ZIP文件
                                                File zipFile = new File(folder, dict.getTitle() + ".zip");
                                                try (OutputStream outputStream = new FileOutputStream(zipFile)) {
                                                    outputStream.write(response.body().bytes());
                                                } catch (Exception e) {
                                                    com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                                                }

                                                // 解压缩ZIP文件
                                                try {
                                                    int wordCount = 0;
                                                    List<Word> saveWords = new ArrayList<>(dict.getWordNumber());

                                                    try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile))) {
                                                        ZipEntry zipEntry;

                                                        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                                                            if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".json")) {
                                                                // Read JSON content line by line
                                                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                                                byte[] buffer = new byte[1024];
                                                                int bytesRead;

                                                                while ((bytesRead = zipInputStream.read(buffer)) != -1) {
                                                                    baos.write(buffer, 0, bytesRead);
                                                                }

                                                                byte[] data = baos.toByteArray();
                                                                try (BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data)))) {
                                                                    String line;
                                                                    while ((line = reader.readLine()) != null) {
                                                                        wordCount++;
                                                                        // Process each line of JSON content
                                                                        JSONObject jsonWord = new JSONObject(line);
                                                                        Log.d("单词行" + wordCount, line);
//                                                                        buildSaveWord(jsonWord, dict.getTitle());
                                                                        saveWords.add(buildSaveWord(jsonWord, dict.getTitle()));
                                                                        try {
                                                                            dialog.setMessage(String.format("正在下载单词(%s/%s)···", wordCount, dict.getWordNumber()));
                                                                        } catch (Exception e) {
                                                                        }
                                                                    }

                                                                    Word.saveAll(saveWords);
                                                                }
                                                            }
                                                        }
                                                    }

                                                    // 下载完成之后清除文件地址
                                                    dict.setWordFileUrl("downloaded");
                                                    dict.setWordNumber(saveWords.size());
                                                    dict.save();
                                                    Intent intent = new Intent(myActivity, UnitActivity.class);
                                                    intent.putExtra("wordCount", wordCount);
                                                    intent.putExtra("dict", dict.getTitle());
                                                    dialog.dismiss();
                                                    startActivityForResult(intent, 100);
                                                } catch (Exception e) {
                                                    com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                                                    MessageUtils.show("解析单词信息出现错误 " + e.getMessage(), myActivity);
                                                }
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call call, IOException e) {
                                            com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                                        }
                                    });
                                } else {
                                    // 直接查询数据库有多少单词
                                    int wordCount = Word.where("dict = ?", dict.getTitle()).count(Word.class);
                                    Intent intent = new Intent(myActivity, UnitActivity.class);
                                    intent.putExtra("wordCount", wordCount);
                                    intent.putExtra("dict", dict.getTitle());
                                    dialog.dismiss();
                                    startActivityForResult(intent, 100);
                                }
                            }
                        }, 1005);

                    }
                }
            }
        });
        tabTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                typeId = state.get(tab.getPosition());
                loadData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    public static Word buildSaveWord(JSONObject jsonWord, String dict) throws JSONException, InterruptedException {
        Word word = new Word();
        word.setWord(jsonWord.getString("headWord"));
        word.setDict(dict);

        try {
            JSONObject jsonContent = jsonWord.getJSONObject("content").getJSONObject("word").getJSONObject("content");

            try {
                word.setUkphone(jsonContent.getString("ukphone"));
            } catch (JSONException e) {
                word.setUkphone(word.getWord());
            }

            try {
                word.setUsphone(jsonContent.getString("usphone"));
            } catch (JSONException e) {
                word.setUsphone(word.getWord());
            }

            try {
                // 设置释义
                word.setWordZh(jsonContent.getJSONArray("trans").getJSONObject(0).getString("tranCn"));
            } catch (JSONException e) {
                word.setWordZh("该单词暂无释义");
            }

            try {
                // 设置例句
                JSONArray jsonArray = jsonContent.getJSONObject("sentence").getJSONArray("sentences");

                String sentences = "";
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {
                        JSONObject sentenceObject = jsonArray.getJSONObject(i);
                        sentences += sentenceObject.getString("sContent") + "<enzh>" + sentenceObject.getString("sCn") + "<split>";
                    } catch (JSONException e) {
                    }
                }
                word.setSentences(sentences);
            } catch (JSONException e) {
                word.setSentences("该单词暂无例句");
            }
        } catch (JSONException e) {
            word.setUkphone(word.getWord());
            word.setUsphone(word.getWord());
            word.setSentences("该单词暂无例句");
        }
        return word;

//        HttpUtils.sendGetRequestStringResponse(CommonUtils.wordChineseUrl + word.getWord(), new HashMap<>(), responseString -> {
//            // 处理请求成功的情况
//            try {
//                JSONObject jsonObject = new JSONObject(responseString);
//                //获得列表
//                JSONArray zhList = jsonObject.getJSONObject("data").getJSONArray("entries");
//                //把物品列表保存到本地
//                String wordZh = "";
//                for (int i = 0, length = zhList.length(); i < length; i++) {
//                    JSONObject zh = zhList.getJSONObject(i);
//                    wordZh += (zh.getString("explain") + "<split>");
//                }
//                word.setWordZh(wordZh);
//
//            } catch (Exception e) {
//                word.setWordZh(word.getWord());
//                com.example.word.util.ExceptionUtils.printExceptionDetail(e);
//            }
//            word.save();
//            Log.d("更新单词释义", word.getWord());
//        });
    }

    //加载数据
    private void loadData() {
        dictList = DataSupport.where("typeId = ?", typeId).find(Dict.class);
        if (dictList != null && dictList.size() > 0) {
            rvDictList.setVisibility(View.VISIBLE);
            llEmpty.setVisibility(View.GONE);
            dictAdapter.addItem(dictList);
        } else {
            rvDictList.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            loadData();//加载数据
        }
    }


    private void saveWord(String wordFileUrl, String bookTitle) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(wordFileUrl).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) {
                    // 创建目标文件夹
                    // 获取应用的私有目录
                    File folder = myActivity.getExternalFilesDir(null);
                    // 保存下载的ZIP文件
                    File zipFile = new File(folder, bookTitle + ".zip");
                    try (OutputStream outputStream = new FileOutputStream(zipFile)) {
                        outputStream.write(response.body().bytes());
                    } catch (Exception e) {
                        com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                    }

                    // 解压缩ZIP文件
                    try {
                        try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile))) {
                            ZipEntry zipEntry;

                            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                                if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".json")) {
                                    // Read JSON content line by line
                                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream))) {
                                        String line;
                                        while ((line = reader.readLine()) != null) {
                                            // Process each line of JSON content
                                            JSONObject jsonWord = new JSONObject(line);
                                            Word word = new Word();
                                            word.setWord(jsonWord.getString("headWord"));
                                            word.setDict(bookTitle);
                                            Log.d("单词行", line);
                                            word.save();
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException | JSONException e) {
                        com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                    }
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                com.example.word.util.ExceptionUtils.printExceptionDetail(e);
            }
        });
    }

}
